package cn.you.GenghisKhan.common.file;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.ArrayList;
import java.util.List;


public class FileTool {
	/** 
	获取列表
	@param fileAbsolutePath  文件地址
	@param extensionname  扩展名
	@return  
	*/
	public static List<String> GetFiles(String fileAbsolutePath, String extensionname)
    {
		 List<String> files=new ArrayList<String>();
         File file = new File(fileAbsolutePath);
         File[] subFile = file.listFiles();

         for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++)
         {
             //判断是否为文件夹
             if (!subFile[iFileLength].isDirectory())
             {
                 String tempName = subFile[iFileLength].getName();
                 //判断是否为xls或xlsx结尾
                 if (tempName.trim().toLowerCase().endsWith(".xls") || 
                         tempName.trim().toLowerCase().endsWith(".xlsx"))
                 {
                     //去掉tXXXX.xls文件的首字母t
                     String fileName = tempName.substring(1);
                     files.add(fileName);
                 }
             }
         }
		return files;
    }
	  /**
     * 将文本文件中的内容读入到buffer中
     * @param buffer buffer
     * @param filePath 文件路径
     * @throws IOException 异常
     * @author cn.outofmemory
     * @date 2013-1-7
     */
    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
        InputStream is = new FileInputStream(filePath);
        String line; // 用来保存每行读取的内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine(); // 读取第一行
        while (line != null) { // 如果 line 为空说明读完了
            buffer.append(line); // 将读到的内容添加到 buffer 中
            line = reader.readLine(); // 读取下一行
        }
        reader.close();
        is.close();
    }

    /**
     * 读取文本文件内容
     * @param filePath 文件所在路径
     * @return 文本内容
     * @throws IOException 异常
     * @author cn.outofmemory
     * @date 2013-1-7
     */
    public static String readFile(String filePath) throws IOException {
        StringBuffer sb = new StringBuffer();
        FileTool.readToBuffer(sb, filePath);
        return sb.toString();
    }
    
    public static File getFile(String fileName) throws Exception{
    	ClassLoader classLoader = FileTool.class.getClassLoader();  
        String urlStr = classLoader.getResource(fileName).getFile();
        String str  = java.net.URLDecoder.decode(urlStr,"UTF-8");
        File file = new File(str);
        return file;
    }
    /**
     * 读取文件放到字节数组中
     * @throws IOException 
     * */
    @SuppressWarnings("resource")
	public static byte[] readFileToBytes(String filefullname) throws IOException{
    	  FileChannel fc = null;  
          try{  
              fc = new RandomAccessFile(filefullname,"r").getChannel();  
              MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();  
              System.out.println(byteBuffer.isLoaded());  
              byte[] result = new byte[(int)fc.size()];  
              if (byteBuffer.remaining() > 0) {  
//                System.out.println("remain");  
                  byteBuffer.get(result, 0, byteBuffer.remaining());  
              }  
              return result;  
          }catch (IOException e) {  
              e.printStackTrace();  
              throw e;  
          }finally{  
              try{  
                  fc.close();  
              }catch (IOException e) {  
                  e.printStackTrace();  
              }  
          }  
        
    }
    
    /**
     * 把字节数组放到文件中 生成文件
     * */
    public static String writeFileForBytes(byte[] filebytes,String filefullname){
    	BufferedOutputStream bos = null;  
        FileOutputStream fos = null;  
        File file = null;  
        try {  
//            File dir = new File(filePath);  
//            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在  
//                dir.mkdirs();  
//            }  
            file = new File(filefullname);  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(filebytes);              
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (IOException e1) {  
                   e1.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
        }
    	return filefullname;
    }
}
